// 社团页
import React, { useCallback, useEffect, useState } from "react";
import {
  Table,
  Input,
  Popconfirm,
  Form,
  message,
  Tag,
  Space,
  Button,
  Modal,
  Radio,
} from "antd";
import request from "../../utils/request";
import {
  ReloadOutlined,
  PlusCircleOutlined,
  SearchOutlined,
} from "@ant-design/icons";

// 可编辑的单元格
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}!`,
            },
          ]}
        >
          <Input />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

function Organization() {
  const [form] = Form.useForm();
  const [orgList, setOrgList] = useState();
  const [total, setTotal] = useState(0);
  const [able, setable] = useState(false);
  const [editingKey, setEditingKey] = useState("");
  const [visible, setVisible] = useState(false);
  const [query, setQuery] = useState({
    org_name: "",
    org_president: "",
    page: 1,
    pagesize: 5,
  });
  // 是否是编辑
  const isEditing = (record) => record._id === editingKey;

  // 获取表单数据
  const getList = useCallback(async () => {
    const { data: res } = await request("/org", { params: query });
    // console.log(res);
    if (res.code !== 1) message.error("获取数据失败！");
    setOrgList(res.data.list);
    setTotal(res.data.total);
  }, [query]);
  useEffect(() => {
    getList();
  }, []);
  // 搜索按钮
  const onFinish = useCallback(({ org_name, org_president }) => {
    query.org_name = org_name;
    query.org_president = org_president;
    setQuery(query);
    getList();
  }, []);
  // 刷新按钮
  const ref = useCallback(() => {
    query.org_name = "";
    query.org_president = "";
    query.page = 1;
    query.pagesize = 5;
    setQuery(query);
    getList();
  }, []);
  // 编辑按钮
  const edit = useCallback((record) => {
    // console.log(record);
    form.setFieldsValue({
      org_name: "",
      org_president: "",
      org_state: 1,
      ...record,
    });
    setEditingKey(record._id);
  }, []);
  // 添加社团按钮
  const addOrg = useCallback(() => {
    form.resetFields();
    setVisible(true);
  }, []);
  // 添加社团确认按钮
  const onCreate = useCallback((val) => {
    console.log("val", val);
    request.post("/org/insert", val).then(({ data }) => {
      console.log("data", data);
    });
    setVisible(false);
  });

  // 保存编辑按钮
  const save = async (id) => {
    const row = await form.validateFields();
    const { data: res } = await request.put("/org/" + id, row);
    if (res.code !== 1) return message.error("修改失败！");
    message.success("修改成功！");
    setEditingKey("");
    getList();
  };
  // 页码改变
  const onChange = useCallback((page, pagesize) => {
    query.pagesize = pagesize;
    query.page = page;
    setQuery(query);
    getList();
  }, []);
  // 确认删除
  const confirmDel = useCallback(async ({ _id }) => {
    const { data: res } = await request.delete("/org/" + _id);
    if (res.code !== 1) return message.error("删除失败！");
    message.success("删除成功！");
    getList();
  }, []);
  // 表格
  const columns = [
    {
      title: "#",
      width: "5%",
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: "社团名",
      width: "20%",
      dataIndex: "org_name",
      editable: true,
    },
    {
      title: "社长",
      width: "20%",
      dataIndex: "org_president",
      editable: true,
    },
    {
      title: "状态",
      width: "15%",
      dataIndex: "org_state",
      editable: true,
      render: (text) =>
        text == 1 ? (
          <Tag color="#2db7f5">启用中</Tag>
        ) : (
          <Tag color="#f50">已禁用</Tag>
        ),
    },
    {
      title: "创建时间",
      width: "20%",
      dataIndex: "setup_time",
      render(text) {
        const date = new Date(text);
        return date.toLocaleDateString();
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <>
            <span>
              <a onClick={() => {
                setable(false)
                save(record._id);
              }} style={{ marginRight: 8 }}>
                保存
              </a>
              <a onClick={() => {
                 setable(false);
                 setEditingKey("");
              }} style={{ paddingRight: 20 }}>
                取消
              </a>
            </span>
            <Popconfirm
              title="确定删除？"
              onCancel={() => message.info("取消删除")}
              okText="确定"
              cancelText="取消"
            >
              <Button type="primary" danger size="small">
                删除
              </Button>
            </Popconfirm>
          </>
        ) : (
          <Space size="middle">
            <Button
              type="primary"
              size="small"
              disabled={editingKey !== ""}
                onClick={() => {
                  setable(true)
                edit(record);
              }}
            >
              修改
            </Button>
            <Popconfirm
              title="确定删除？"
              onCancel={() => message.info("取消删除")}
              onConfirm={() => confirmDel(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="primary" danger size="small">
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  // 分页
  const pagination = {
    size: "small",
    total,
    showTitle: false,
    page: query.page,
    pageSize: query.pagesize,
    pageSizeOptions: [1, 3, 5, 10],
    showTotal: (total) => `共${total}条`,
    showSizeChanger: true,
    onChange,
  };
  // 表单列的配置
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <>
      {/* 头部搜索栏 */}
      <Form layout="inline" onFinish={onFinish}>
        <Form.Item name="org_name" label="社团名">
          <Input />
        </Form.Item>
        <Form.Item name="org_president" label="社团会长">
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            <SearchOutlined />
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={ref}>
            <ReloadOutlined />
            刷新
          </Button>
        </Form.Item>
      </Form>
      {/* 添加社团按钮 */}
      <Button
        type="primary"
        disabled={able}
        style={{ marginTop: 50, marginBottom: 10 }}
        onClick={addOrg}
      >
        <PlusCircleOutlined />
        添加社团
      </Button>
      {/* 可编辑表格 */}
      <Form form={form} component={false}>
        <Table
          rowKey={(row) => row._id}
          components={{ body: { cell: EditableCell } }}
          bordered
          dataSource={orgList}
          pagination={pagination}
          columns={mergedColumns}
          scroll={{ x: "1100px", y: "calc(100vh - 400px)" }}
        />
      </Form>
      {/* 弹出新建表单 */}
      <Modal
        visible={visible}
        title="添加社团"
        okText="添加"
        cancelText="取消"
        onCancel={() => {
          setVisible(false);
        }}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log("Validate Failed:", info);
            });
        }}
      >
        <Form form={form} layout="vertical" name="form_in_modal">
          <Form.Item
            name="org_name"
            label="社团名称"
            rules={[
              {
                required: true,
                message: "请输入社团名称",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="org_president"
            label="社团会长"
            rules={[
              {
                required: true,
                message: "请输入社团会长名字",
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}

export default Organization;
